package ObjectMapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class ObjectMapperExample {
    public static void main(String[] args) {
        ObjectMapper objectMapper = new ObjectMapper();

        // 示例 1: Java对象序列化为JSON字符串
        Person person = new Person("John", 30);
        try {
            // 将 Java 对象序列化为 JSON
            String jsonString = objectMapper.writeValueAsString(person);
            System.out.println("序列化后的JSON字符串: " + jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 示例 2: 将JSON字符串反序列化为Java对象
        String json = "{\"name\":\"Jane\",\"age\":25}";
        try {
            // 将 JSON 字符串反序列化为 Java 对象
            Person deserializedPerson = objectMapper.readValue(json, Person.class);
            System.out.println("反序列化后的Person对象: " + deserializedPerson.getName() + ", " + deserializedPerson.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 示例 3: 处理嵌套JSON结构 (List)
        String jsonArray = "[{\"name\":\"John\",\"age\":30}, {\"name\":\"Jane\",\"age\":25}]";
        try {
            // 反序列化为 List<Person>
            List<Person> people = objectMapper.readValue(jsonArray, new TypeReference<List<Person>>(){});
            for (Person p : people) {
                System.out.println("姓名: " + p.getName() + ", 年龄: " + p.getAge());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// Person 类定义
class Person {
    private String name;
    private int age;

    // 使用 @JsonCreator 注解指定构造器用于反序列化
    @JsonCreator
    public Person(@JsonProperty("name") String name, @JsonProperty("age") int age) {
        this.name = name;
        this.age = age;
    }

    // Getters 和 Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}